package com.itheima.daiotuwang.interceptors;

import com.itheima.daiotuwang.pojo.JwtUtil;
import com.itheima.daiotuwang.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //该方法会在请求处理之前被调用，通常用于进行一些预处理操作，比如权限验证、请求日志记录等。如果返回 true，则请求会继续被处理；如果返回 false，则请求处理流程会中断
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         //查看是否有请求头Authorization中是否带着 token
        String token = request.getHeader("Authorization");
        if(token==null){
            //没有token
            response.setStatus(401);
            response.getWriter().write("没有权限");
            return false;
        }
        else{
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);//相当于将该用户的信息存到该线程上
            return true;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }




}
